package com.zrb.mobile;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.zrb.mobile.adapter.ContentSettingAdapter;
import com.zrb.mobile.adapter.RadioItem;
import com.zrb.mobile.common.NightConfig;
import com.zrb.mobile.register.User_phone_login;
import com.zrb.mobile.ui.CenterProgressWebView;
import com.zrb.mobile.ui.CenterProgressWebView.IOnJsPrompt;
import com.zrb.applib.utils.AppSetting;
import com.zrb.mobile.utility.CollectionHelper;
import com.zrb.mobile.utility.CollectionHelper.onCollectionListener;
import com.zrb.mobile.utility.DialogBuilder;
import com.zrb.mobile.utility.ProgressDialogEx;
import com.zrb.mobile.utility.Tip;

public class News_WebContentActivity extends BaseActivity implements OnClickListener, OnCheckedChangeListener, OnSeekBarChangeListener, IOnJsPrompt, onCollectionListener  {

	private final int SPLASH_DISPLAY_LENGHT = 2000; // 延迟1秒
	CenterProgressWebView mWebView;
	private Dialog tmpdialSetting;
	ContentSettingAdapter tmpsettingAdapter;
	private String url;
	private String mtitle;
	View nightmask;
	private boolean isNight=false;
	private int fontSize=9;
	int newid;
	String title;
	TextView btnfavorite;
	Tip progTip;
	boolean isFavorite=false;
	CollectionHelper mCollectionHelper;
	
	@Override
	protected void onCreate(Bundle bundle) {
		super.onCreate(bundle);
        if(NightConfig.getInstance(this).getNightModeSwitch()){
             isNight=true;
        }
        
 		setContentView(R.layout.news_web_content);
		if (bundle != null)
			restoreSelf(bundle);
		else {
			newid = this.getIntent().getIntExtra("newid", -1);
			title = this.getIntent().getStringExtra("title");
		}
		initview();
	}
	
	@Override
	 protected  void onSaveInstanceState(Bundle outState)
     {
         super.onSaveInstanceState(outState);
         outState.putInt("newid", newid);
         outState.putString("title", title);
     }

     private void restoreSelf(Bundle savedInstanceState)
     {
    	 newid = savedInstanceState.getInt("newid");
    	 title = savedInstanceState.getString("title");
     }

	
    private void initview(){
    	
    	mCollectionHelper = new CollectionHelper(this.getApplicationContext(),1);
		mCollectionHelper.setOnCollectionListener(this);
    	
    	nightmask=this.findViewById(R.id.night_mode_overlay);
    	if(isNight) nightmask.setVisibility(View.VISIBLE);
    	
    	this.findViewById(R.id.title_left_root).setOnClickListener(this);
		this.findViewById(R.id.btn_share).setOnClickListener(this);
      	this.findViewById(R.id.btn_font).setOnClickListener(this);
     	
     	btnfavorite=(TextView)this.findViewById(R.id.btn_favorite);
     	btnfavorite.setVisibility(View.VISIBLE);
     	btnfavorite.setOnClickListener(this);
        
        // tmpfavorite.setVisibility(View.VISIBLE);
        // tmpfavorite.setOnClickListener(this);
      	showfavoriteState();
     	
        mWebView=(CenterProgressWebView)this.findViewById(R.id.webView1);
        mWebView.setOnPageListener(mpagelistenr);
       // mWebView.addJavascriptInterface(this, "localApi");
        mWebView.setOnJsPromptListener(this);
       // http://backend.zhaorongbao.com:8090/newsapp/newsDetails?id=26
		// String url="file:///android_asset/detail/detail.html";
	    String url=AppSetting.BASE_URL+"newsapp/newsDetails?id="+newid;
 		mWebView.loadUrl(url);
    }
   
    private void showfavoriteState(){
    	/*if(AppSetting.curUser==null) return;
     	isFavorite=	mCollectionHelper.isExistId(newid,true);
     	if(isFavorite){ 
     		btnfavorite.setSelected(true);
     		btnfavorite.setText("已关注");
     	};*/
    	
    }
    
    private CenterProgressWebView.IOnPageListener mpagelistenr=new CenterProgressWebView.IOnPageListener(){

		@Override
		public void onPageStarted(String url) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onPageFinished(String url) {
			// TODO Auto-generated method stub
			if(isNight) mWebView.loadUrl("javascript:load_night()");
			
			float fontsize= NightConfig.getInstance(News_WebContentActivity.this).getFontSize();
			mWebView.loadUrl("javascript:doZoom("+fontsize+")");
//			else
//				mWebView.loadUrl("javascript:load_day()");
		}

		@Override
		public void notifyPageStarted() {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void notifyPageFinished() {
			// TODO Auto-generated method stub
			
		}
    	
    	
    };
    
	
    View Settingmask;
    View cancelBtn;
    ListView tmpsetlistView;
	private void Setting(){
 
		DialogBuilder tmpbuild = new DialogBuilder(this);
		tmpbuild.setContentView(R.layout.detail_more_title_dialog);

		View rootview = tmpbuild.getCurContentView();
 		Settingmask=	rootview.findViewById(R.id.detail_more_title_layout);
		Settingmask.setBackgroundColor(this.getResources().getColor(
						              isNight ? R.color.detail_more_bg_night
								              : R.color.detail_more_bg));
  		
 		cancelBtn =rootview.findViewById(R.id.cancel_btn);
 		cancelBtn.setOnClickListener(this);
		cancelBtn.setBackgroundDrawable(this.getResources().getDrawable(
				                        isNight ? R.drawable.detail_more_cancel_btn_night
						                        : R.drawable.detail_more_cancel_btn));
	
  		rootview.findViewById(R.id.empty_overlay).setOnTouchListener(new OnTouchListener(){
 		    @Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				if(tmpdialSetting!=null) tmpdialSetting.dismiss();
				return true;
			}} );
				
  		tmpsetlistView = (ListView) rootview.findViewById(R.id.detail_more_title_lv);
		tmpsettingAdapter = new ContentSettingAdapter(this,isNight);
		tmpsettingAdapter.setOnCheckedChangeListener(this);
		tmpsettingAdapter.setOnGroupChangeListener(monCheckchange);
		tmpsettingAdapter.setOnSeekBarChangeListener(this);
 	
		tmpsettingAdapter.CurrentDatas.add(new RadioItem("夜间模式", "1"));
	//	tmpsettingAdapter.CurrentDatas.add(new RadioItem("字体间距", "2"));
		tmpsettingAdapter.CurrentDatas.add(new RadioItem("字体大小", "2"));

		tmpsetlistView.setAdapter(tmpsettingAdapter);
		tmpdialSetting = tmpbuild.createDialog(this, R.style.bottomInDialog);
		// tmpdial.show();
     }
	
	RadioGroup.OnCheckedChangeListener monCheckchange=new RadioGroup.OnCheckedChangeListener(){

		@Override
		public void onCheckedChanged(RadioGroup group, int checkedId) {
			// TODO Auto-generated method stub
			//CommonUtil.showToast("onRadioGroupCheckedChanged", News_WebContentActivity.this);
			float fontsize=9;
			if(R.id.rb_font_size_small==checkedId)     { mWebView.loadUrl("javascript:doZoom(9)");fontsize=9;}
			else if(R.id.rb_font_size_medium==checkedId){  mWebView.loadUrl("javascript:doZoom(10.5)");fontsize=(float) 10.5;}
			else if(R.id.rb_font_size_big==checkedId) { mWebView.loadUrl("javascript:doZoom(12)");fontsize=12;}
			else                                       { mWebView.loadUrl("javascript:doZoom(13)");fontsize=13;}
			
			NightConfig.getInstance(News_WebContentActivity.this).setFontSize(fontsize);
 		}

	 };  
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
		  case R.id.cancel_btn:
			  if(tmpdialSetting!=null) tmpdialSetting.dismiss();
			 
			  break;
		  case  R.id.title_left_root:
			  if(mWebView.canGoBack()) {
				  mWebView.goBack();return;
			  };
			  this.finish();
			  break;
		  case  R.id.btn_share:
			  shareLink();
			  break;
		  case  R.id.btn_font:
			  Setting();
			  break;
		  case  R.id.btn_favorite:
			  onClickCollect(newid);
			  break;
 		}
 	}
	
	private void shareLink(){
 		 // String imageLink=AppSetting.BASE_URL+"newsapp/newsDetails?id="+newid;
		  Intent intent = new Intent(News_WebContentActivity.this,News_ShareActivity.class);
		  intent.putExtra("title", title);
		 // intent.putExtra("url",imageLink);
		  intent.putExtra("url", mWebView.getUrl());
		  startActivity(intent);
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		// TODO Auto-generated method stub
		//CommonUtil.showToast("onCheckedChanged", News_WebContentActivity.this);
		 
		if(isChecked){ 
			mWebView.loadUrl("javascript:load_night()");
			nightmask.setVisibility(View.VISIBLE);
			isNight=true;
			cancelBtn.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.detail_more_cancel_btn_night));
			Settingmask.setBackgroundColor(this.getResources().getColor(R.color.detail_more_bg_night));
			tmpsettingAdapter.SetNightlist(tmpsetlistView,true);
		}
		else{
			mWebView.loadUrl("javascript:load_day()");
			nightmask.setVisibility(View.GONE);
			isNight=false;
			cancelBtn.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.detail_more_cancel_btn));
			Settingmask.setBackgroundColor(this.getResources().getColor(R.color.detail_more_title_bg));
			tmpsettingAdapter.SetNightlist(tmpsetlistView,false);
		//  Setttin    detail_more_bg_night
		}
 	}
 	//OnSeekBarChangeListener
	@Override
	public void onProgressChanged(SeekBar seekBar, int progress,
			boolean fromUser) {
		// TODO Auto-generated method stub
		//CommonUtil.showToast("onProgressChanged", News_WebContentActivity.this);
	}

	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void PromptInfo(String message, String defaultValue) {
		// TODO Auto-generated method stub
		//1|gap:["service", "action", "callbackId"]
		
		//CommonUtil.showToast(message+"|"+defaultValue, this);
		if(TextUtils.isEmpty(message)) return;
		if(!message.contains(",")) return;
		//CommonUtil.showToast(message+"|"+defaultValue, this);
		 String[] tmpArr=message.split(",");
/*		 if(tmpArr.length==3){
			 newid=Integer.parseInt(tmpArr[0]);
			 title=tmpArr[1];
			 String url=AppSetting.BASE_URL+"newsapp/newsDetails?id="+newid;
		     mWebView.loadUrl(url);
			 return;
		 }*/
  	  	  Intent it = new Intent(this, Search_resultActivity.class);
		  it.putExtra("tag", tmpArr[1]+",");
		  it.putExtra("value", Integer.parseInt(tmpArr[0]));
	 	  startActivity(it);
	}

	@Override
	protected void	onActivityResult(int requestCode, int resultCode, Intent data){
 	   
		switch (resultCode) { // resultCode为回传的标记，我在B中回传的是RESULT_OK
		case RESULT_OK:
  			showfavoriteState();
			if(!isFavorite) onClickCollect(newid);
			break;
		default:
			break;
		}
 	    super.onActivityResult(requestCode, resultCode, data);
   } 
	 
	private void showloading() {
		if (progTip == null)
			progTip = ProgressDialogEx.Show(this, " title", "添加关注中..", true,
					true);
		else
			progTip.Show("添加关注中...");
	}
	
	public void onClickCollect(int newsId) {
		// TODO Auto-generated method stub
 		if(AppSetting.curUser==null){
 			 Intent it = new Intent(this, User_phone_login.class);
 			 it.putExtra("forResult", true);
			 this.startActivityForResult(it, 100);
		    return;
		}
 		//mCollectionHelper.onClickCollect(newsId,!isFavorite,true);
  	}
	
	@Override
	public void onCollectionEvent() {
		// TODO Auto-generated method stub
		//showToast(!isFavorite ?"已关注":"取消关注", Project_info_lience.this);
		isFavorite=!isFavorite;
           btnfavorite.setSelected(isFavorite); 
           btnfavorite.setText(isFavorite?"已关注":"关 注");
           btnfavorite.setEnabled(false);
	         new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                	btnfavorite.setEnabled(true);
                }

        }, 2000);
	}
	
	@Override
	public void ReceivedTitle(String mtitle) {
		// TODO Auto-generated method stub
		// CommonUtil.showToast(title, News_WebContentActivity.this);
		title=mtitle;
	}

	private void showToast(String msg,Context mcontext){
 		Toast tmpTip=Toast.makeText(mcontext, msg, Toast.LENGTH_SHORT);
		tmpTip.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
		tmpTip.show();
	}

 
	
}
